<template>
  <BasicModal
    v-bind="$attrs"
    @ok="handleSubmint"
    okText="提交"
    @register="register"
    :title="modalTitle"
    width="40%"
    :min-height="500"
    @visible-change="handleVisibleChange"
  >
    <div class="pt-3px pr-3px">
      <BasicForm @register="registerFormByGroup" />
    </div>
  </BasicModal>
</template>

<script lang="ts" setup>
  import { BasicModal, useModal } from '/@/components/Modal';

  import { computed } from 'vue';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form/index';
  // import fileWay from '/@/views/project/tag/components/fileWay.vue';
  import { ParamsByGroupModel } from './type';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { getFormErrorMessage, checkName } from '/@/utils/index';

  const props = defineProps({
    formType: {
      type: Object,
      default: () => {},
    },
    // 使用场景
    type: {
      type: String,
      default: '',
    },
  });
  // 分组配置表单内容
  const schemasByGroup: FormSchema[] = [
    {
      field: 'groupName',
      component: 'Input',
      label: '组名：',
      helpMessage: '总长度为200字符，一个中文等于8个字符，数字/字母/英文下划线占1个字符',
      dynamicDisabled: () => {
        return props.formType.operationType === 2;
      },
      colProps: {
        span: 24,
      },
      rules: [
        {
          required: true,
          validator: async (_rule, value) => checkName(value, '组名'),
          trigger: ['change', 'blur'],
        },
      ],
    },
    {
      field: 'refreshRate',
      dynamicDisabled: () => {
        return props.formType.operationType === 2;
      },
      component: 'InputNumber',
      label: '刷新率：',
      defaultValue: 1000,
      colProps: {
        span: 24,
      },
      componentProps: {},
      rules: [
        {
          required: true,
          message: '请输入刷新率',
          trigger: ['change', 'blur'],
        },
      ],
      suffix: '(毫秒)',
    },
    {
      field: 'deadZone',
      component: 'InputNumber',
      label: '死区：',
      dynamicDisabled: () => {
        return props.formType.operationType === 2;
      },
      defaultValue: 0,
      colProps: {
        span: 24,
      },
      rules: [
        {
          required: true,
          message: '请输入死区',
          trigger: ['change', 'blur'],
        },
      ],
      componentProps: {},
    },
    {
      dynamicDisabled: () => {
        return props.formType.operationType === 2;
      },
      field: 'isActivation',
      component: 'RadioGroup',
      label: '是否激活:',
      colProps: {
        span: 24,
      },
      defaultValue: '1',
      componentProps: {
        options: [
          {
            label: '是',
            value: '1',
          },
          {
            label: '否',
            value: '0',
          },
        ],
      },
      rules: [
        {
          required: true,
          // message: '请选择预配置',
          validator: async (_rule, value) => {
            if (!value) {
              /* eslint-disable-next-line */
              return Promise.reject('请选择是否激活');
            }
            return Promise.resolve();
          },
          trigger: ['change', 'blur'],
        },
      ],
    },
  ];
  const [
    registerFormByGroup,
    {
      validateFields: validateFieldsByGroup,
      setFieldsValue: setFieldsValueByGroup,
      resetFields: resetFieldsByGroup,
      updateSchema: updateSchemaByGroup,
    },
  ] = useForm({
    labelWidth: 120,
    schemas: schemasByGroup,
    showActionButtonGroup: false,
    actionColOptions: {
      span: 24,
    },
  });
  const [register] = useModal();
  const { createMessage } = useMessage();
  const { t } = useI18n();

  const emit = defineEmits(['submitSuccess']);

  let modalTitle = computed(() => {
    return `${
      props.formType.operationType === 0
        ? '新增'
        : props.formType.operationType === 1
        ? '编辑'
        : '查看'
    }分组配置`;
  });

  // 初始化
  async function initData() {
    if (props.formType.id) {
      try {
        let resByGroup: any = await props.formType.getGroupInfo([
          props.formType.driveId,
          props.formType.id,
        ]);
        // 添加表单值
        let setValueByGroup: any = {
          groupName: resByGroup.Name,
          refreshRate: resByGroup.UpdateRate,
          isActivation: resByGroup.IsActive ? '1' : '0',
          deadZone: resByGroup.DeadBand,
        };

        updateSchemaByGroup({
          field: 'groupName',
          componentProps: {
            disabled: resByGroup.GroupType === 2,
          },
        });

        setFieldsValueByGroup(setValueByGroup);
      } catch (error) {}
    }
  }

  // 提交
  async function handleSubmint() {
    try {
      let res: any = {};
      let resByApi: any = {};

      res = await validateFieldsByGroup();
      let paramsByGroups: ParamsByGroupModel = {
        Name: res.groupName,
        UpdateRate: res.refreshRate,
        IsActive: +res.isActivation === 1,
        DeadBand: res.deadZone,
      };
      if (props.formType.id) {
        await props.formType.updateGroupInfo([
          props.formType.driveId,
          props.formType.id,
          paramsByGroups,
        ]);
      } else {
        await props.formType.addGroupInfo([props.formType.driveId, paramsByGroups]);
      }

      createMessage.success(t('layout.setting.operatingTitle'));
      emit('submitSuccess', resByApi);
    } catch (error) {
      getFormErrorMessage(error);
    }
  }
  // 弹窗显示和关闭的钩子
  function handleVisibleChange(visible) {
    if (visible) {
      initData();
    } else {
      updateSchemaByGroup({
        field: 'groupName',
        componentProps: {
          disabled: false,
        },
      });
      resetFieldsByGroup();
    }
  }
</script>

<style scoped lang="less">
  .tabs-form {
    width: 100%;
    padding: 5px 10px;
    box-sizing: border-box;
    border: 1px solid #d9d9d9;
    border-radius: 2px;
  }

  ::v-deep(.ant-cascader-menu) {
    height: 300px;
  }
</style>
